package org.jeecg.modules.xxgx.djgl.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.xxgx.common.enums.TdyslxDmEnum;
import org.jeecg.modules.xxgx.djgl.entity.CsXxDkdj;
import org.jeecg.modules.xxgx.djgl.entity.CsXxDkdjCezs;
import org.jeecg.modules.xxgx.djgl.entity.CsXxDkdjExt;
import org.jeecg.modules.xxgx.djgl.entity.CsXxDkdjmx;
import org.jeecg.modules.xxgx.djgl.entity.cezs.Cezs;
import org.jeecg.modules.xxgx.djgl.entity.tdyw.*;
import org.jeecg.modules.xxgx.djgl.service.ICsXxDkdjCezsService;
import org.jeecg.modules.xxgx.djgl.service.ICsXxDkdjExtService;
import org.jeecg.modules.xxgx.djgl.service.ICsXxDkdjService;
import org.jeecg.modules.xxgx.djgl.service.ICsXxDkdjmxService;
import org.jeecg.modules.xxgx.djgl.vo.CsXxDkdjPage;
import org.jeecg.modules.xxgx.fjys.vo.FjysVO;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * @Description: 待开单据
 * @Author: jeecg-boot
 * @Date: 2023-08-18
 * @Version: V1.0
 */
@Api(tags = "待开单据")
@RestController
@RequestMapping("/xxgx/djgl/csXxDkdj")
@Slf4j
public class CsXxDkdjController {
    @Autowired
    private ICsXxDkdjService csXxDkdjService;
    @Autowired
    private ICsXxDkdjmxService csXxDkdjmxService;
    @Autowired
    private ICsXxDkdjExtService iCsXxDkdjExtService;
    @Autowired
    private ICsXxDkdjCezsService iCsXxDkdjCezsService;

    /**
     * 分页列表查询
     *
     * @param csXxDkdj
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "待开单据-分页列表查询")
    @ApiOperation(value = "待开单据-分页列表查询", notes = "待开单据-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<CsXxDkdj>> queryPageList(CsXxDkdj csXxDkdj,
                                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                 HttpServletRequest req) {
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        QueryWrapper<CsXxDkdj> queryWrapper = QueryGenerator.initQueryWrapper(csXxDkdj, req.getParameterMap());
        queryWrapper.eq("company_id", user.getCompanyId());
        queryWrapper.orderByDesc("djrq");
        Page<CsXxDkdj> page = new Page<CsXxDkdj>(pageNo, pageSize);
        IPage<CsXxDkdj> pageList = csXxDkdjService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param csXxDkdjPage
     * @return
     */
    @AutoLog(value = "待开单据-添加")
    @ApiOperation(value = "待开单据-添加", notes = "待开单据-添加")
    @RequiresPermissions("xxgx.djgl:cs_xx_dkdj:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody CsXxDkdjPage csXxDkdjPage) {
        CsXxDkdj csXxDkdj = new CsXxDkdj();
        BeanUtils.copyProperties(csXxDkdjPage, csXxDkdj);
        csXxDkdjService.saveMain(csXxDkdj, csXxDkdjPage.getCsXxDkdjmxList());
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param csXxDkdjPage
     * @return
     */
    @AutoLog(value = "待开单据-编辑")
    @ApiOperation(value = "待开单据-编辑", notes = "待开单据-编辑")
    @RequiresPermissions("xxgx.djgl:cs_xx_dkdj:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody CsXxDkdjPage csXxDkdjPage) {
        CsXxDkdj csXxDkdj = new CsXxDkdj();
        BeanUtils.copyProperties(csXxDkdjPage, csXxDkdj);
        CsXxDkdj csXxDkdjEntity = csXxDkdjService.getById(csXxDkdj.getId());
        if (csXxDkdjEntity == null) {
            return Result.error("未找到对应数据");
        }
        csXxDkdjService.updateMain(csXxDkdj, csXxDkdjPage.getCsXxDkdjmxList());
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "待开单据-通过id删除")
    @ApiOperation(value = "待开单据-通过id删除", notes = "待开单据-通过id删除")
    @RequiresPermissions("xxgx.djgl:cs_xx_dkdj:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        csXxDkdjService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "待开单据-批量删除")
    @ApiOperation(value = "待开单据-批量删除", notes = "待开单据-批量删除")
    @RequiresPermissions("xxgx.djgl:cs_xx_dkdj:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.csXxDkdjService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "待开单据-通过id查询")
    @ApiOperation(value = "待开单据-通过id查询", notes = "待开单据-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<CsXxDkdj> queryById(@RequestParam(name = "id", required = true) String id) {
        CsXxDkdj csXxDkdj = csXxDkdjService.getById(id);
        //处理特定业务数据
        CsXxDkdjExt csXxDkdjExt = iCsXxDkdjExtService.lambdaQuery().eq(CsXxDkdjExt::getFromid, id).one();
        if(csXxDkdjExt != null){
            if(TdyslxDmEnum.JZFW.getValue().equals(csXxDkdj.getTdyslxdm())){
                csXxDkdj.setTdywJzfw(JSON.parseObject(csXxDkdjExt.getTdywInfo(), Jzfw.class));
            } else if(TdyslxDmEnum.HWYSFW.getValue().equals(csXxDkdj.getTdyslxdm())){
                csXxDkdj.setTdywHwysfwList(JSONArray.parseArray(csXxDkdjExt.getTdywInfo(), Hwysfwmx.class));
            } else if(TdyslxDmEnum.BDCXS.getValue().equals(csXxDkdj.getTdyslxdm())){
                csXxDkdj.setTdywBdcxs(JSON.parseObject(csXxDkdjExt.getTdywInfo(), Bdcxsfw.class));
            } else if(TdyslxDmEnum.BDCJYZLFW.getValue().equals(csXxDkdj.getTdyslxdm())){
                csXxDkdj.setTdywBdcjyzlfw(JSON.parseObject(csXxDkdjExt.getTdywInfo(), Bdcjyzlfw.class));
            } else if(TdyslxDmEnum.LKYSFW.getValue().equals(csXxDkdj.getTdyslxdm())){
                csXxDkdj.setTdywLkysfwList(JSONArray.parseArray(csXxDkdjExt.getTdywInfo(), Lkysfwmx.class));
            }
            //处理附加要素
            if(StringUtils.isNotBlank(csXxDkdjExt.getFjysInfo())){
                csXxDkdj.setFjysList(JSONArray.parseArray(csXxDkdjExt.getFjysInfo(), FjysVO.class));
            }
        }
        //处理差额征收
        List<CsXxDkdjCezs> list = iCsXxDkdjCezsService.lambdaQuery().eq(CsXxDkdjCezs::getFromid, id).list();
        List<Cezs> cezsList = new ArrayList<>();
        if(!list.isEmpty()){
            for (int i = 0; i < list.size(); i++) {
                Cezs cezs = new Cezs();
                CsXxDkdjCezs csXxDkdjCezs = list.get(i);
                BeanUtils.copyProperties(csXxDkdjCezs,cezs);
                cezsList.add(cezs);
            }
            csXxDkdj.setCezsList(cezsList);
        }

        if (csXxDkdj == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(csXxDkdj);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "待开单据明细通过主表ID查询")
    @ApiOperation(value = "待开单据明细主表ID查询", notes = "待开单据明细-通主表ID查询")
    @GetMapping(value = "/queryCsXxDkdjmxByMainId")
    public Result<List<CsXxDkdjmx>> queryCsXxDkdjmxListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<CsXxDkdjmx> csXxDkdjmxList = csXxDkdjmxService.selectByMainId(id);
        return Result.OK(csXxDkdjmxList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param csXxDkdj
     */
    @RequiresPermissions("xxgx.djgl:cs_xx_dkdj:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CsXxDkdj csXxDkdj) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<CsXxDkdj> queryWrapper = QueryGenerator.initQueryWrapper(csXxDkdj, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //配置选中数据查询条件
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }
        //Step.2 获取导出数据
        List<CsXxDkdj> csXxDkdjList = csXxDkdjService.list(queryWrapper);

        // Step.3 组装pageList
        List<CsXxDkdjPage> pageList = new ArrayList<CsXxDkdjPage>();
        for (CsXxDkdj main : csXxDkdjList) {
            CsXxDkdjPage vo = new CsXxDkdjPage();
            BeanUtils.copyProperties(main, vo);
            List<CsXxDkdjmx> csXxDkdjmxList = csXxDkdjmxService.selectByMainId(main.getId());
            vo.setCsXxDkdjmxList(csXxDkdjmxList);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "待开单据列表");
        mv.addObject(NormalExcelConstants.CLASS, CsXxDkdjPage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("待开单据数据", "导出人:" + sysUser.getRealname(), "待开单据"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("xxgx.djgl:cs_xx_dkdj:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<CsXxDkdjPage> list = ExcelImportUtil.importExcel(file.getInputStream(), CsXxDkdjPage.class, params);
                for (CsXxDkdjPage page : list) {
                    CsXxDkdj po = new CsXxDkdj();
                    BeanUtils.copyProperties(page, po);
                    csXxDkdjService.saveMain(po, page.getCsXxDkdjmxList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

}
